<?php
 
namespace App\Http\Controllers;

use App\Models\User;
 
class AuthController extends Controller
{
     // 无需登录
     protected $noNeedAuth = ['login'];

     /**
      * Create a new AuthController instance.
      *
      * @return void
      */
     public function __construct()
     {
         $this->middleware('auth:api', ['except' => $this->noNeedAuth]);
     }
 
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function login($user_id)
    {
        $user = User::where('id', $user_id)->first();
        if (!$user) {
            $this->error('no user_id');
        }
        if (! $token = auth('api')->login($user)) {
           $this->result('create token fail');
        }
 
        $this->respondWithToken($token);
    }
 
    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function user()
    {
        return auth('api')->user();
    }
 
    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function logout()
    {
        auth('api')->logout();
        $this->success('Successfully logged out');
    }
 
    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function refresh()
    {
        $this->respondWithToken(auth('api')->refresh());
    }
 
    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
       $this->success('ok', [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }
}